<template>
  <div>
    <van-search
      v-model.trim="keyword"
      show-action
      label="商品"
      placeholder="请输入搜索关键词"
      background="#f66"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="history">
      <div class="his" @click="enterResult(his)" v-for="his in histories" :key="his">{{his}}</div>

    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      keyword: '',
      histories: localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : []
    }
  },
  methods: {
    enterResult (keyword) {
      // 点击搜索记录 搜索
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword
        }
      })
    },
    onSearch () {
      if (this.keyword === '') {
        return
      }
      // 存储搜索关键字
      // 先取出来  转换成数组  操作数组 再存回去
      let histories = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : []
      histories.unshift(this.keyword)
      // 数组如何去重
      histories = [...new Set(histories)]
      localStorage.setItem('history', JSON.stringify(histories))
      // 进入搜索的结果页  传 关键字参数 传过去
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword: this.keyword
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.history{
  display: flex;

  .his{
    padding: 0 10px;
    line-height: 30px;
    background-color: #f1f1f1;
    border-radius: 15px;
    margin-top: 5px;
    margin-left: 10px;
  }
}
</style>
